Function can call themselves recursively. Each time execution
passes into the function the local variables are (re)created. There
is a special keyword: $self
, which can be used to force a
function to refer to itself. This is only necessary if you plan to
rename the function after it has been created.
fac = function ( a )
{
if(a <= 1)
{
return 1;
else
return a*fac (a-1); // return a*$self (a-1);
}
};
In the previous example a factorial computation is performed using
recursion
. In the second return statement, the function calls
itself until a≤1. In the event that the function is later
copied to another variable, and the original destroyed, the
function will no longer work. To avoid this, use the special
keyword $self
in place of the function self-reference.